import count from '@dfeidao/atom-nodejs/db/count';
import query from '@dfeidao/atom-nodejs/db/query';
import format from '@dfeidao/atom-nodejs/dt/format';
import parse from '@dfeidao/atom-nodejs/dt/parse';
// import log from '@dfeidao/atom-nodejs/logger/log';
import { IncomingHttpHeaders } from 'http';
import { productid, systemid } from '../../atom/config';

interface Message {
	filter: {
		pn: number;
		start_time: string;
		end_time: string;
		plan_name: string;
		take_effect?: number;
	};
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	// log('Service begin path:c:\Users\32645\Desktop\kh\src\plan-cb\zj-000001\s001,action_id:' + action_id);

	// log('Service end path:c:\Users\32645\Desktop\kh\src\plan-cb\zj-000001\s001,action_id:' + action_id);

	const f: { productid: string; take_effect?: number; start_date?: {}; $and?: Array<{}>; plan_name?: {}; } = { productid };

	if (message.filter) {
		// 有筛选条件
		const start_time = message.filter.start_time;
		const end_time = message.filter.end_time;
		if (start_time && end_time) {
			const s = parse(start_time);
			const e = parse(end_time);
			f.$and = [{ start_date: { $gte: s } }, { start_date: { $lte: e } }];
		} else if (start_time) {
			// { productid: 'smart_security',start_time:  { $gte: s }}
			// 	// { field: { $gte: value } }
			const s = parse(start_time);
			f.start_date = { $gte: s };
		} else if (end_time) {
			const e = parse(end_time);
			// { productid: 'smart_security',start_time:  { $gte: s }}
			f.start_date = { $lte: e };
		}
		const plan_name = message.filter.plan_name;
		f.plan_name = {
			$like: '%' + plan_name + '%'
		};
		if (message.filter.take_effect) {
			const take_effect = message.filter.take_effect;
			f.take_effect = take_effect;
		}
	}


	const q = query(action_id, session_id, systemid);
	q.prepare('plan', ['plan_no', 'plan_name', 'plan_cla_attr_name', 'plan_type_name', 'start_date', 'plan_cycle', 'call_period', 'take_effect', 'plan_implement_status'], f, 20, message.filter.pn, [], []);
	const [res1] = await q.exec<{ start_date: string; }>();

	const res = res1.map((v) => {
		const nowdate = new Date(v.start_date).getTime();
		const newdate = format(nowdate, 'YYYY-MM-DD HH:mm');
		return { ...v, newdate };
	});

	const { prepare: p, exec } = count(action_id, session_id, systemid);
	p('plan', f);

	const [c] = await exec();

	return {
		data: { res, c, res1 }
	};
}
